package com.teamall.framework.util;

import java.io.File;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.teamall.framework.exception.BaseAppException;

/**
 * 发送邮件辅助类
 */
//@Service("sendMailUtils")
public class SendMailUtils{
    /**
     * 发送Text邮件
     * @param toAddress邮件接收者地址  
     * @param title 邮件主题  
     * @param content 邮件内容
     * @param attachFileNames 附件名称 
     * @return
     * @throws BaseAppException 
     */
    public static boolean sendTextMail(String title,String content,String toAddress) throws BaseAppException {     
    	SendMailUtils sendMailUtils = new SendMailUtils();
    	MailInfo mailInfo = new MailInfo();
    	mailInfo.setSubject(title);
    	mailInfo.setContent(content);
    	mailInfo.setToAddress(toAddress);
    	
        //判断是否需要身份认证  
        MyAuthenticator authenticator = null;
        Properties properties = mailInfo.getProperties();  
        try {  
        	if (mailInfo.isValidate()) {  
        		//如果需要身份认证，则创建一个密码验证器  
        		authenticator = new MyAuthenticator(mailInfo.getUsername(), mailInfo.getPassword());  
        	}  
        	//根据邮件会话属性和密码验证器构造一个发送邮件的session  
        	Session sendMailSession = Session.getDefaultInstance(properties, authenticator);  
            Message mailMessage = new MimeMessage(sendMailSession);//根据session创建一个邮件消息   
            Address from = new InternetAddress(mailInfo.getFromAddress());//创建邮件发送者地址  
            mailMessage.setFrom(from);//设置邮件消息的发送者  
            Address to = new InternetAddress(mailInfo.getToAddress());//创建邮件的接收者地址  
            mailMessage.setRecipient(Message.RecipientType.TO, to);//设置邮件消息的接收者  
            mailMessage.setSubject(mailInfo.getSubject());//设置邮件消息的主题  
            mailMessage.setSentDate(new Date());//设置邮件消息发送的时间  
            mailMessage.setText(mailInfo.getContent());//设置邮件消息的主要内容  
              
            //MimeMultipart类是一个容器类，包含MimeBodyPart类型的对象  
            Multipart mainPart = new MimeMultipart();  
            MimeBodyPart messageBodyPart = new MimeBodyPart();//创建一个包含附件内容的MimeBodyPart  
            //设置HTML内容  
            messageBodyPart.setContent(mailInfo.getContent(),"text/html; charset=utf-8");  
            mainPart.addBodyPart(messageBodyPart);  
  
            //存在附件  
            String[] filePaths = mailInfo.getAttachFileNames();  
            if (filePaths != null && filePaths.length > 0) {  
                for(String filePath:filePaths){  
                    messageBodyPart = new MimeBodyPart();  
                    File file = new File(filePath);   
                    if(file.exists()){//附件存在磁盘中  
                        FileDataSource fds = new FileDataSource(file);//得到数据源  
                        messageBodyPart.setDataHandler(new DataHandler(fds));//得到附件本身并至入BodyPart  
                        messageBodyPart.setFileName(file.getName());//得到文件名同样至入BodyPart  
                        mainPart.addBodyPart(messageBodyPart);  
                    }  
                }  
            }  
              
            //将MimeMultipart对象设置为邮件内容     
            mailMessage.setContent(mainPart);  
            Transport.send(mailMessage);//发送邮件  
            return true;  
        } catch (Exception e) {  
            e.printStackTrace();    
        }  
        return false;  
    }     
    
    /**
     * 发送Text邮件
     * @param toAddress邮件接收者地址  
     * @param title 邮件主题  
     * @param content 邮件内容
     * @param attachFileNames 附件名称 
     * @return
     * @throws BaseAppException 
     */
    public static boolean sendHtmlMail(String title,String content,String toAddress) throws BaseAppException {
    	SendMailUtils sendMailUtils = new SendMailUtils();
    	MailInfo mailInfo = new MailInfo();
    	mailInfo.setSubject(title);
    	mailInfo.setContent(content);
    	mailInfo.setToAddress(toAddress);
//    	mailInfo.setAttachFileNames(attachFileNames);
    	
        //判断是否需要身份认证  
        MyAuthenticator authenticator = null;  
        Properties properties = mailInfo.getProperties(); 
        try{  
        	if (mailInfo.isValidate()) {  
        		// 如果需要身份认证，则创建一个密码验证器  
        		authenticator = new MyAuthenticator(mailInfo.getUsername(), mailInfo.getPassword());  
        	}  
        	
        	// 根据邮件会话属性和密码验证器构造一个发送邮件的session  
        	Session sendMailSession = Session.getDefaultInstance(properties, authenticator);  
            Message mailMessage = new MimeMessage(sendMailSession);//根据session创建一个邮件消息   
            Address from = new InternetAddress(mailInfo.getFromAddress());//创建邮件发送者地址  
            mailMessage.setFrom(from);//设置邮件消息的发送者  
            Address to = new InternetAddress(mailInfo.getToAddress());//创建邮件的接收者地址  
            mailMessage.setRecipient(Message.RecipientType.TO, to);//设置邮件消息的接收者  
            mailMessage.setSubject(mailInfo.getSubject());//设置邮件消息的主题  
            mailMessage.setSentDate(new Date());//设置邮件消息发送的时间  
              
            //MimeMultipart类是一个容器类，包含MimeBodyPart类型的对象  
            Multipart mainPart = new MimeMultipart();  
            MimeBodyPart messageBodyPart = new MimeBodyPart();//创建一个包含HTML内容的MimeBodyPart  
            //设置HTML内容  
            messageBodyPart.setContent(mailInfo.getContent(),"text/html; charset=utf-8");  
            mainPart.addBodyPart(messageBodyPart);  
              
            //存在附件  
            String[] filePaths = mailInfo.getAttachFileNames();  
            if (filePaths != null && filePaths.length > 0) {  
                for(String filePath:filePaths){  
                    messageBodyPart = new MimeBodyPart();  
                    File file = new File(filePath);   
                    if(file.exists()){//附件存在磁盘中  
                        FileDataSource fds = new FileDataSource(file);//得到数据源  
                        messageBodyPart.setDataHandler(new DataHandler(fds));//得到附件本身并至入BodyPart  
                        messageBodyPart.setFileName(file.getName());//得到文件名同样至入BodyPart  
                        mainPart.addBodyPart(messageBodyPart);  
                    }  
                }  
            }  
              
            //将MimeMultipart对象设置为邮件内容     
            mailMessage.setContent(mainPart);  
            Transport.send(mailMessage);//发送邮件  
            return true;  
        }catch (Exception e) {  
            e.printStackTrace();  
            throw new BaseAppException(e.getMessage());
        }  
    }  
    
    
    /**
     * 邮箱@符号后面大写转小写
     * @param email	邮箱
     * @return email 转换后邮箱
     * */
    public static String tabMail(String email){
    	String[] emailArr = email.split("@");
    	String s = emailArr[1].toLowerCase();
    	return emailArr[0]+"@"+s;
    }

    public static void main(String[] args) {
         //163邮箱注册
//    	 mailInfo.setMailServerHost("smtp.163.com");  
//       mailInfo.setMailServerPort("smtp");  
//       mailInfo.setUsername("xu252659774");  
//       mailInfo.setPassword("xu305997985");// 您的邮箱密码  
//       mailInfo.setFromAddress("xu252659774@163.com");  
//       mailInfo.setToAddress("252659774@qq.com");  
//         SendMailUtils sendMailUtils = new SendMailUtils();
          StringBuffer sb=new StringBuffer("点击下面链接激活账号，48小时生效，否则重新注册账号，链接只能使用一次，请尽快激活！</br>");
          sb.append("<a href=\"http://localhost:8080/teamall/user/tmUser/emailCheckActive.do?loginName=");
          sb.append("1"); 
          sb.append("\">http://localhost:8080/teamall/user/tmUser/emailCheckActive.do?loginName="); 
          sb.append("1");
          sb.append("</a>");
          String content = sb.toString();
          System.out.println("准备发送邮件，内容为："+sb.toString());
          try {
        	  SendMailUtils.sendHtmlMail("注册成功",content,"1182397459@qq.com");
		} catch (BaseAppException e) {
			e.printStackTrace();
		}// 发送html格式  
          System.out.println("发送结束");
    }
    
}

class MyAuthenticator extends Authenticator {  
    private String username = null;  
    private String password = null;  
  
    public MyAuthenticator() {  
    };  
  
    public MyAuthenticator(String username, String password) {  
        this.username = username;  
        this.password = password;  
    }  
  
    protected PasswordAuthentication getPasswordAuthentication() {  
        return new PasswordAuthentication(username, password);  
    }  
  
}  
